#!/bin/bash
set -e
if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash build.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || "$1" = "/" ]]; then echo "请输入正确的构建路径"; exit 1; fi
if [[ ! "$2" =~ ^/.* || "$2" = "/" ]]; then echo "请输入正确的安装路径"; exit 1; fi

buildpath=$1
installpath=$2
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi
if [ ! -d "$buildpath" ]; then mkdir -p $buildpath; else mv $buildpath $buildpath`date "+%y%m%d%H%M%S"` && mkdir -p $buildpath; fi
if [ ! -d "$installpath" ]; then mkdir -p $installpath; else mv $installpath $installpath`date "+%y%m%d%H%M%S"` && mkdir -p $installpath; fi

yum install -y m4 environment-modules systemd-devel
source /etc/profile
module purge

dep_dir="dependency"
bash $dep_dir/bisheng-compiler-2.1.0.sh $buildpath $installpath
module use $installpath/bisheng-compiler-2.1.0
module load $installpath/bisheng-compiler-2.1.0/bisheng_modulefiles

bash $dep_dir/hmpi-1.1.1.sh $buildpath $installpath
module use $installpath/hmpi-1.1.1
module load $installpath/hmpi-1.1.1/hmpi_modulefiles


bash OpenLB-1.5-0.sh $buildpath $installpath

mkdir -p pkg/OpenLB-1.5-0-hpc && cp -r $installpath/* pkg/OpenLB-1.5-0-hpc/
cat>"pkg/OpenLB-1.5-0-hpc/run.sh"<<EOF
#!/bin/bash
yum install -y m4 environment-modules systemd-devel csh time patch libatomic perl-Data-Dumper \\
autoconf automake libtool numactl binutils valgrind flex wget tar libatomic gcc-c++ 
source /etc/profile &> /dev/null 
current_dir=\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" &> /dev/null && pwd)
for d in \$(ls \$current_dir)
do
    [[ ! \$d =~ "OpenLB" && ! -f "\$current_dir/\$d" ]] && cd \$current_dir/\$d && module use \$(pwd) && module load \$(pwd)/*modulefiles
done
cd \$current_dir
EOF

cd pkg/ && tar zcvf OpenLB-1.5-0-hpc.tar.gz OpenLB-1.5-0-hpc

rm -rf $buildpath $installpath

